#!/usr/bin/env python
#coding: utf-8
#author: Wesley
import os
from django.conf.urls import url
from .handlers import code
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse

Error_Not_Login =  JsonResponse({'retcode': 99,'msg': '未登录'})
# Error_Not_Parent = JsonResponse({'retcode': 100,'msg': u'请以家长帐号登录'})

def CheckUserIsParentForApiCaller(request,*args,**kwargs):
    #if 'ut' not in request.session :
    #    return Error_Not_Login

    realCall = kwargs.pop('_viewFunc')
    return realCall(request,*args,**kwargs)


urlpatterns_api = []

def addPreCheck(urlpatterns,checkFunC):
    checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)

urlpatterns_api_agrs = [
    # 此处不会走lib.common.AbstractHandler.dispatch, 普通的django view
    (r'^sendcode/$', code.handler.handle_send),
    (r'^checkcode/$', code.handler.handle_check),
]

addPreCheck(urlpatterns_api_agrs,CheckUserIsParentForApiCaller)

urlpatterns = urlpatterns_api
